import React, { useEffect } from 'react'
import { Form, Button } from 'antd'

function Input2(props) {
  useEffect(() => {
    console.info(`create new Item ${props.name}`)
    return () => {
      console.info(`Item destory Item ${props.name}`)
    }
  }, [])
  return props.children
}

function Child(props) {
  console.info(props.name, '  rerender')
  useEffect(() => {
    console.info(`create new Child ${props.name}`)
    return () => {
      console.info(`Item destory Child ${props.name}`)
    }
  }, [])
  return props.name || 'etst'
}

class ListDemo extends React.Component {
  state = {
    arr: [{
      id: 1,
      value: 'test1'
    }, {
      id: 2,
      value: 'test2'
    }]
  }

  removeArr = (id) => {
    const { arr } = this.state
    const index = arr.findIndex((item) => (item.id === id))
    arr.splice(index, 1)
    this.setState({ arr: [...arr] })
  }

  render() {
    const onFinish = values => {
      console.log('Received values of form: ', values)
    }
    console.info('rerender')
    return (
      <Form onFinish={onFinish}
        initialValues={{
          list: [{
            test: 'aaa'
          }, {
            test: 'bbb'
          }]
        }}
      >
        <Form.List name={['list']} >
          {(fields, { add, remove }) => {
            console.info(fields)
            return (
              <div>
                {fields.map(field => {
                  const { key, name, fieldKey } = field
                  return (
                    <Form.Item label="数组项" {...field}>
                      <Input2 name={fieldKey} ><Child name={fieldKey} /></Input2>
                    </Form.Item>
                  )
                })}
                <Button onClick={() => remove(0)} >删除2</Button>
                <Button onClick={() => add()} >添加2</Button>
              </div>
            )
          }}
        </Form.List>
        {
          this.state.arr.map((item) => {
            return (
              <div>
                <Input2 name={item.id} ><Child name={item.value} /></Input2>
                <Button onClick={() => this.removeArr(item.id)} >删除</Button>
              </div>)
          })
        }
        <Button type="primary" htmlType="submit">Submit</Button>
      </Form>
    )
  }
}
export default ListDemo
